package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

// ClientPost 定义了博客文章的结构
type ClientPost struct {
	ID      int    `json:"id"`
	Title   string `json:"title"`
	Content string `json:"content"`
	Author  string `json:"author"`
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: go run blogclient.go <action> [<params>]")
		return
	}

	switch os.Args[1] {
	case "list":
		listPosts()
	case "post":
		if len(os.Args) != 5 {
			fmt.Println("Usage: go run blogclient.go post <title> <content> <author>")
			return
		}
		createPost(os.Args[2], os.Args[3], os.Args[4])
	case "delete":
		if len(os.Args) != 3 {
			fmt.Println("Usage: go run blogclient.go delete <id>")
			return
		}
		id := os.Args[2]
		deletePost(id)
	default:
		fmt.Println("Unknown action")
	}
}

func listPosts() {
	response, err := http.Get("http://localhost:8080/posts")
	if err != nil {
		fmt.Println("Error fetching posts:", err)
		return
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	var posts []ClientPost
	err = json.Unmarshal(body, &posts)
	if err != nil {
		fmt.Println("Error decoding posts:", err)
		return
	}

	for _, post := range posts {
		fmt.Printf("ID: %d\nTitle: %s\nContent: %s\nAuthor: %s\n\n", post.ID, post.Title, post.Content, post.Author)
	}
}

func createPost(title, content, author string) {
	post := ClientPost{
		Title:   title,
		Content: content,
		Author:  author,
	}

	postJSON, err := json.Marshal(post)
	if err != nil {
		fmt.Println("Error encoding post:", err)
		return
	}

	response, err := http.Post("http://localhost:8080/posts", "application/json", bytes.NewBuffer(postJSON))
	if err != nil {
		fmt.Println("Error creating post:", err)
		return
	}
	defer response.Body.Close()

	if response.StatusCode == http.StatusCreated || response.StatusCode == http.StatusOK {
		fmt.Println("Post created successfully")
	} else {
		fmt.Printf("Failed to create post, status code: %d\n", response.StatusCode)
	}
}

func deletePost(id string) {
	client := &http.Client{}
	req, err := http.NewRequest(http.MethodDelete, "http://localhost:8080/posts/"+id, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusOK {
		fmt.Println("Post deleted successfully")
	} else {
		fmt.Printf("Failed to delete post, status code: %d\n", resp.StatusCode)
	}
}
